﻿using Abp.Application.Services;
using Abp.Domain.Repositories;
using Abp.UI;
using AbpDemo.Entity;
using study.Demo.Dto;
using study.Students.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace study.Students
{
    public class StudentAppService : AsyncCrudAppService<Student, StudentDto, int, PagedStudentResultRequestDto, CreateStudentDto, StudentDto>
    {
        private readonly IRepository<Student> _studentRepository;
        public StudentAppService(IRepository<Student> studentRepository) : base(studentRepository)
        {
            _studentRepository = studentRepository;
        }

        /// <summary>
        /// 获取学生数据
        /// </summary>
        /// <returns></returns>
        public List<Student> OutPutAllStudent(StudentDto input)
        {
            var studentList = _studentRepository.GetAll();
            if (!string.IsNullOrEmpty(input.Keyword))
            {
                studentList = studentList.Where(s => (s.Name.Contains(input.Keyword) || s.Code.Contains(input.Keyword)));
            }
            return studentList.ToList();
        }

        /// <summary>
        /// 更新学生
        /// </summary>
        /// <returns></returns>
        public void UpdateStudent(StudentDto input)
        {
            Student student = new Student() { Id = Convert.ToInt32(input.Id), Code = input.Code, Name = input.Name };
            _studentRepository.Update(student);
        }

        /// <summary>
        /// 删除学生
        /// </summary>
        /// <returns></returns>
        public void DelStudent(StudentDto input)
        {
            Student student = _studentRepository.Get(Convert.ToInt32(input.Id));
            _studentRepository.Delete(student);
        }

        /// <summary>
        /// 新增学生
        /// </summary>
        /// <returns></returns>
        public void CreateStudent(CreateStudentDto input)
        {
            var stuById = _studentRepository.GetAll().Where(c => c.Code == input.Code);
            if (stuById.Count() == 0)
            {
                var student = new Student() { Name = input.Name, Code = input.Code };
                _studentRepository.Insert(student);
            }
            else
                throw new UserFriendlyException("新增学生失败", "已有该学号，请重新输入");
        }       
    }
}
